# -*- coding:utf-8 -*-
# Author:lixuecheng
from flask import Flask,redirect
import socket
import threading
import os
import time
import  json
# from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
socket.setdefaulttimeout(30)


def socket_port(ip, port):
    """
    输入IP和端口号，扫描判断端口是否占用
    """
    try:
        if port >= 65535:
            return False, '端口过大'
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = s.connect_ex((ip, port))
        if result == 0:
            return False, '已占用'
        else:
            return True, ''
    except Exception as e:
        return False, str(e)


class DoWeb:
    def __init__(self, port=None, is_debug=False):
        self.cf = []
        self.wss={}
        if port is None:
            self.port = 10000
            while self.port < 65535:

                c, _ = socket_port('127.0.0.1', self.port)
                if c:
                    break
                else:
                    self.port += 1
            else:
                raise Exception('当前无端口可用')
        else:
            c, v = socket_port('127.0.0.1', int(port))
            if c:
                self.port = int(port)
            else:
                raise Exception(v)
        self.pid = os.getpid()
        self.app = Flask('WebApp_'+str(self.pid), static_url_path='')
        # self.sockets = Sockets(self.app)
        if is_debug:
            self.app.debug = True
        self.endport_index = 0

    def add_route(self, rule, func, methods=['get']):
        self.endport_index += 1
        self.app.add_url_rule(str(rule), methods=methods,
                              view_func=func, endpoint=str(self.endport_index))


    # def add_route_ws(self, rule):
    #     self.endport_index += 1
    #     if '/<name>' not in rule:
    #         print('路径需要添加唯一名称/<name>')
    #         return 
    #     self.sockets.add_url_rule(str(rule), '',
    #                               f=self._ws_func)

    # def _ws_func(self,ws,name):
    #     # print(name)
    #     self.wss[name]=ws
    #     while not ws.closed:
    #         time.sleep(1)

    # def send_ws(self,name,data):
    #     self.wss[name].send(data)

    # def close_ws(self,name=None):
    #     if name is None:
    #         for i in self.wss:
    #             i.close()
    #     else:
    #         self.wss[name].close()



    def add_static_file(self, rule):
        self.endport_index += 1
        app = self.app
        f_n = ''
        if rule.startswith('/'):
            f_n = rule[1:]
        else:
            f_n = rule

        def f():
            return app.send_static_file(f_n)
        # print(__file__,__package__)
        p = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')
        file = os.path.join(p, f_n)
        if not os.path.exists(file):
            print('[warn] {} 目录下没有文件：{}'.format(p, f_n))
        else:

            self.app.add_url_rule(str(os.path.dirname(rule)), methods=['get'],
                              view_func=f, endpoint=str(self.endport_index))

    def start(self):

        self.add_route('/close_'+str(self.pid), self.close)
        self.add_route('/close_'+str(13500123000), self.close)
        print('close with http://localhost:' +
              str(self.port)+'/close_'+str(self.pid))

        self.app.run(host='0.0.0.0', port=int(self.port))
        # server = pywsgi.WSGIServer(('0.0.0.0',int(self.port)),application=self.app,handler_class=WebSocketHandler)
        # print('server started')
        # server.serve_forever()


    def close(self):
        for i in self.cf:
            try:
                i()
            except:
                pass
        a = os.popen('taskkill /pid {} /f'.format(str(self.pid)))
        b = a.read()
        print(b)
        return b

    def add_close_func(self, *f):
        self.cf = f

        # self.app.run(host='0.0.0.0', port=int(self.port))





# d = DoWeb()
# d.add_route_ws('/test1/<name>')
# def hi():
#     d.send_ws('test1',1)
#     d.send_ws('test1','2')

#     return 'ok'
# d.add_route('/test2',hi)
# d.start()



# d.add_static_file('/1.html')
# d.add_static_file('/js/2.html')

# d.add_route('/test/<name>', hi)
# d.start()
# time.sleep(5)
# d.close()
# app.add_url_rule('/', methods=['post','get'], view_func=hi)

# if __name__ == '__main__':
#     app.debug=True
#     app.run(host="0.0.0.0", port=8081)
